package cn.edu.sctu.sctu_lysd.presenter;

import android.content.Context;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.IOException;

import cn.edu.sctu.sctu_lysd.bean.ChatToken;
import cn.edu.sctu.sctu_lysd.bean.JsonBaseBeen;
import cn.edu.sctu.sctu_lysd.bean.LoginSuccessData;
import cn.edu.sctu.sctu_lysd.bean.UserProfile;
import cn.edu.sctu.sctu_lysd.biz.GetUserMessage;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.net.NetService;
import cn.edu.sctu.sctu_lysd.net.RetrofitHelper;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wangfuxin on 2017-04-17.
 */

public class WelcomePresenter implements GetUserMessage.Presenter {

    public static final int CALL_PROFILE_ERROR = 40000901;

    private NetService service;
    private SharePreferenceUtils sharePreferenceUtils;
    private Context mContext;
    private GetUserMessage.View mView;

    private Call<JsonBaseBeen<UserProfile>> userProfileCall;
    private Call<ResponseBody> refreshTokenCall;

    public WelcomePresenter(Context mContext, GetUserMessage.View mView) {
        this.mContext = mContext;
        this.mView = mView;
    }

    @Override
    public void start() {

        RetrofitHelper helper = RetrofitHelper.getInstance();

        service = (NetService) helper.getService(NetService.class);

        sharePreferenceUtils = SharePreferenceUtils.getInstance(mContext);

    }

    @Override
    public void getUserProfile() {

        userProfileCall = service.getUserProfile(sharePreferenceUtils.getString(CacheKeyConfig.CACHE_ACCESS_TOKEN));

        userProfileCall.enqueue(new Callback<JsonBaseBeen<UserProfile>>() {
            @Override
            public void onResponse(Call<JsonBaseBeen<UserProfile>> call, Response<JsonBaseBeen<UserProfile>> response) {

                L.e("onResponsewfx", response.toString());

                if (response.body().getMeta().getCode() == 200) {

                    UserProfile data = response.body().getData();

                    mView.getUserProfileSuccess(data);


                    sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_USER_LOGIN, data.getLogin());
                    sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_USER_AVATAR_URL, data.getAvatarUrl());
                    sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_USER_NICKNAME, data.getNickname());
                    sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_IS_DEPOSIT,data.getDeposit());
                    sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_USER_ID,data.getId());

                    L.e("getAvatarUrl", data.getAvatarUrl());

                } else {

                    mView.getUserProfileFailed();

                }
            }

            @Override
            public void onFailure(Call<JsonBaseBeen<UserProfile>> call, Throwable t) {
                mView.getUserProfileFailed();
            }
        });


    }

    @Override
    public String getInputString(TextView view) {
        return null;
    }

    @Override
    public void refreshToken() {

        refreshTokenCall = service.refreshToken(sharePreferenceUtils.getString(CacheKeyConfig.CACHE_REFRESH_TOKEN));

        refreshTokenCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                L.e("onResponserefresh", response.toString());

                try {
                    Gson gson = new Gson();

                    String json = response.body().string();

                    String access_token = json.substring(2, 14);

                    if (access_token.equals("access_token")) {


                        LoginSuccessData loginSuccessData = gson.fromJson(json, LoginSuccessData.class);

                        cacheLoginMessage("Bearer " + loginSuccessData.getAccess_token(), loginSuccessData.getRefresh_token());

                        mView.refreshTokenSuccess();
                    } else {

                        mView.refreshTokenFailed();
                    }

                } catch (Exception e) {

                    mView.refreshTokenFailed();

                }


            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

                mView.refreshTokenFailed();
            }
        });


    }

    @Override
    public void getChatToken(final long userId) {
        service.getChatToken(userId).enqueue(new Callback<JsonBaseBeen<ChatToken>>() {
            @Override
            public void onResponse(Call<JsonBaseBeen<ChatToken>> call, Response<JsonBaseBeen<ChatToken>> response) {

                L.e("CACHE_CHAT_TOKEN"," " + userId  + response.toString());

                if (response.code() == 200 && response.body().getMeta().getCode() == 200){
                    SharePreferenceUtils.getInstance(mContext).setCache(CacheKeyConfig.CACHE_CHAT_TOKEN,response.body().getData().getToken());

                    L.e("CACHE_CHAT_TOKEN",response.body().getData().getToken());

                    mView.getChatTokenSuccess(response.body().getData().getToken());

                }
            }

            @Override
            public void onFailure(Call<JsonBaseBeen<ChatToken>> call, Throwable t) {

                L.e("CACHE_CHAT_TOKEN",t.getMessage());

                mView.getChatTokenFailed();

            }
        });
    }


    public void cacheLoginMessage(String access_token, String refresh_token) {
        sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_ACCESS_TOKEN, access_token);
        sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_REFRESH_TOKEN, refresh_token);
    }
}
